import Vue from "vue";
import App from "./App.vue";
import router from "./router/index";

import i18n from './lang'
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";

import "./icons";
import "./styles/index.scss";
import 'element-ui/lib/theme-chalk/display.css';

import "./lib/tron.js"

Vue.config.productionTip = false;
// Vue.use(ElementUI);
Vue.use(ElementUI, {
  // size: Cookies.get('size') || 'medium', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value)
})

Vue.prototype.$ctr_kid='TL1rM9eafLeqz6LEVkLMDMbkBNPystZ9Zx'
Vue.prototype.$ctr_kio='TB8h3XaLoDjQdj9x7HX2SPDxUuxRBS3kaH'
Vue.prototype.$ctr_kia='TUKDvWbgE86LDBL4EmGzx3EQ4RnkycWyAB'
Vue.prototype.$ctr_kis='TPXKEoAL2Yx8b9akCV7bzv1KdbG7S2dPUw'

Vue.prototype.$showLoding = function (b) {
  if (this.alertObj) {
    this.alertObj.type = "loading"
    this.alertObj.message = this.$t('popup.loading')
    this.alertObj.isShow = true
  }
}
Vue.prototype.$showFail = function (msg) {
  if (this.alertObj) {
    this.alertObj.isShow = true
    this.alertObj.message = msg || this.$t('popup.fail')
    this.alertObj.type = "fail"
  }
}
Vue.prototype.$showSuccess = function (msg) {
  if (this.alertObj) {
    this.alertObj.isShow = true
    this.alertObj.message = msg || this.$t('popup.success')
    this.alertObj.type = "success"
  }
}


Vue.prototype.$tronAsyncFc = async function (contractAddr, asyncfName, fname, value, ...param) {
  try {
    let cct = await loadContract(contractAddr);
    let res = await cct[fname](...param)[asyncfName]({
      feeLimit: 200000000,
      callValue: value || 0,
      shouldPollResponse: true,
    });
    return res;
  } catch (e) {
    //"Confirmation declined by user"
    console.error(e);
    if (e == "Confirmation declined by user") {
      throw new Error(this.$t('popup.cancel'));
    }
  }
}

Vue.prototype.$tronSend = async function (contractAddr, fname, value, ...param) {
  return this.$tronAsyncFc(contractAddr, "send", fname, value, ...param);
}

Vue.prototype.$tronCall = async function (contractAddr, fname, value, ...param) {
  return this.$tronAsyncFc(contractAddr, "call", fname, value, ...param);
}

Vue.prototype.$alert = function (msg, type) {
  this.$message({
    message: msg,
    type: type || "warning",
  });
}

/**
 * 
 * @param {*} symbol 要授权的token symbol
 * @param {*} spender 授权给这个地址
 * @param {*} amount 授权金额
 * @param {*} backF 回调函数
 */
Vue.prototype.$approve = async function (symbol, spender, amount) {
  if (!amount || amount < 1) {
    this.$alert(this.$t('popup.mustApproveAmount'))
    return
  }
  if (symbol=='usdt' && ((spender=='kid'&&amount<100)||(spender=='kia'&&amount<200))) {
    this.$alert(this.$t('popup.inputApproveAmount'))
    return
  }
  this.$showLoding(true)

  amount = mathUpToken(symbol, amount)

  this.$tronSend(addrMap[symbol], 'approve', 0, addrMap[spender], amount).then(res => {
    if (res && (res == true || res.success == true)) {
      this.$showSuccess(this.$t('popup.approveSuccessed'))
    } else {
      this.$showFail()
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}

/**
 * 购买
 * @param {*} payToken 支付的token symbol 
 * @param {*} payTokenAmount  支付token金额
 * @param {*} reference 上级
 * @param {*} isSafeTransfer 是否安全支付 
 */
Vue.prototype.$buyToken = async function (payToken, payTokenAmount, isSafeTransfer) {
  if (!payTokenAmount || ((payToken=='kid'&&payTokenAmount < 100)||payToken=='kia'&&payTokenAmount < 200)) {
    this.$alert(this.$t('popup.inputBuyAmount'))
    return
  }
  this.$showLoding(true)
  let ref=getReference();
  if(!ref){
    ref=localStorage.getItem('sysref')
    ref=ref+""
    ref=ref.length>10?ref:"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"
  }
  this.$tronSend(addrMap[payToken], 'buyToken', 0, mathUpToken(payToken, payTokenAmount), ref, isSafeTransfer).then(res => {
    if (res && (res == true || res.success == true)) {
      this.$updateAsset("usdt", "b", true);
      this.$updateAsset(payToken, "b", true);
      this.$showSuccess(this.$t('popup.buySuccess'))
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}


/**
 * 挖矿
 * @param {*} payToken 支付的token symbol 
 * @param {*} payTokenAmount  支付token金额
 * @param {*} reference 上级
 * @param {*} isSafeTransfer 是否安全支付 
 */
Vue.prototype.$digOfKitKia = async function (payTokenAmount, isSafeTransfer) {
  if (!payTokenAmount || payTokenAmount < 1) {
    this.$alert(this.$t('popup.outOfStock'))
    return
  }
  this.$showLoding(true)
  this.$tronSend(addrMap['kia'], 'depositCToken', 0, mathUpToken('kia', payTokenAmount), isSafeTransfer).then(res => {
    if (res && (res == true || res.success == true)) {
      this.$showSuccess(this.$t('popup.depositedSuccessed'))
      this.$updateAsset('kit', "b", true);
      this.$updateAsset('kia', "b", true);
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}

/**
 * 挖矿
 * @param {*} payToken 支付的token symbol 
 * @param {*} payTokenAmount  支付token金额
 * @param {*} reference 上级
 * @param {*} isSafeTransfer 是否安全支付 
 */
Vue.prototype.$dig = async function (payToken, payTokenAmount, isSafeTransfer) {
  if (!payTokenAmount || payTokenAmount < 1) {
    this.$alert(this.$t('popup.mustApproveAmount'))
    return
  }
  this.$showLoding(true)
  this.$tronSend(addrMap[payToken], 'exchange', 0, mathUpToken(payToken, payTokenAmount), isSafeTransfer).then(res => {
    if (res && (res == true || res.success == true)) {
      this.$showSuccess(this.$t('popup.depositedSuccessed'))
      this.$updateAsset(digMap[payToken], "b", true);
      this.$updateAsset(payToken, "d", true);
      this.$updateAsset(payToken, "g", true);
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}

/**
 * 加速
 * @param {*} payToken 支付的token symbol 
 * @param {*} payTokenAmount  支付token金额
 * @param {*} reference 上级
 * @param {*} isSafeTransfer 是否安全支付 
 */
Vue.prototype.$quicken = async function (payToken, payTokenAmount, isSafeTransfer) {
  if (!payTokenAmount || payTokenAmount < 1) {
    this.$alert(this.$t('popup.mustApproveAmount'))
    return
  }
  this.$showLoding(true)
  this.$tronSend(addrMap[payToken], 'depositDToken', 0, mathUpToken(payToken, payTokenAmount), isSafeTransfer).then(res => {
    if (res && (res == true || res.success == true)) {
      this.$showSuccess(this.$t('popup.depositedSuccessed'))
      this.$updateAsset('kio', "b", true);
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}




/**
 * 
 * @param {*} symbol 
 * @param {*} status  b：余额，d:挖矿中
 */
Vue.prototype.$withdrawOfD = function (symbol, isSafeTransfer) {

  this.$showLoding(true)
  let thiz = this;
  this.$tronSend(addrMap[symbol], 'withdraw' + symbolMap[digMap[symbol]] + 'TokenAll', 0, isSafeTransfer).then(b => {
    if (b) {
      this.$showSuccess(this.$t('popup.extractedSuccessed'))
      thiz.asset.d[digMap[symbol]] = 0
      thiz.$updateAsset(digMap[symbol], "d", true);
    } else {
      this.$showFail(this.$t('popup.extractedFailed'))
    }
  })
}
/**
 * 
 * @param {*} symbol 
 * @param {*} status  b：余额，d:挖矿中
 */
Vue.prototype.$withdrawTokenAll = function (symbol, isSafeTransfer) {
  this.$showLoding(true)
  this.$tronSend(addrMap[symbol], 'withdrawTokenAll', 0, addrMap['usdt'], isSafeTransfer).then(b => {
    if (b) {
      this.$updateAsset(symbol, symbol == 'kid' ? 'y1' : 'y2');
      this.$showSuccess(this.$t('popup.extractedSuccessed'))
    } else {
      this.$showFail(this.$t('popup.extractedFailed'))
    }
  })
}



var symbolConvertMap = { 'kid': 'kio', 'kia': 'kis' }

/**
 * 
 * @param {*} symbol 
 * @param {*} status  b：余额，d:挖矿中
 */
Vue.prototype.$withdraw = function (symbol) {

  this.$showLoding(true)
  let thiz = this;
  this.$tronSend(addrMap[symbol], 'update' + symbolMap[symbol] + 'TokenAmount', 0).then(b => {
    if (!b || b.length == 0) {
      this.$showSuccess(this.$t('popup.extractedSuccessed'))
      thiz.$updateAsset(symbol, "g", true);
      thiz.$updateAsset(symbol, "b", true);
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}

/**
 * 
 * @param {*} symbol 
 * @param {*} status  b：余额，d:挖矿中
 */
let mgtime =1000 * 60 * 10
Vue.prototype.$updateAsset = function (symbol, status, flush) {
  let k = window.dftAddr() + ":" + symbol + ":" + status
  let ktime = k + ":time"
  let thiz = this;
  if (flush !== true) {
    let lastUpdateTime = localStorage.getItem(ktime);
    lastUpdateTime=lastUpdateTime?(parseInt(lastUpdateTime)+mgtime):lastUpdateTime;
    let noewTime=Date.now()
    
    if (lastUpdateTime && lastUpdateTime>noewTime ) {
      if (thiz.asset[status] && thiz.asset[status][symbol] !== undefined) {
        let v = localStorage.getItem(k)
        if ((v&&v!=="0") && !isNaN(v)) {
          thiz.asset[status][symbol] = v
          console.log("数据没变，刷新太频繁，取缓存：" + k + "----" + v)
          return;
        }
      }
    }
  }
  connectWallt(() => {
    let ctaddr = addrMap[symbol]
    if ((status == 'd' && symbol == 'kis') || (status == 'y1' || status == 'y2')) {
      this.$tronCall(ctaddr, 'tokenUserAmountOf', 0, (status == 'y1' || status == 'y2') ? addrOfusdt : addrOfkia, dftAddr()).then(b => {
        b=b||0        
			        thiz.asset[status][symbol] = mathDownToken(status == 'd' ? symbol : 'usdt', b)
        localStorage.setItem(k, thiz.asset[status][symbol]);
        localStorage.setItem(ktime, Date.now());
        console.log("刷新数据，存缓存：" + k + "----" + thiz.asset[status][symbol])
      })
    } else {
      let fname = { 'b': 'balanceOf', 'g': 'getUserWaiting' + symbolMap[symbol] + 'TokenAmount', 'd': 'user' + symbolMap[digMap[symbol]] + 'TokenAmoutOf' }
      fname = fname[status]
      fname = symbol == 'kio' && status == 'd' ? 'userATokenAmoutOf' : fname
      let logtxt = status + '----' + symbol + "----" + fname + '--' + ctaddr;
      console.log(logtxt)
      this.$tronCall(ctaddr, fname, 0, dftAddr()).then(b => {
        b=b||0
        thiz.asset[status][symbol] = mathDownToken(symbol, b)
        localStorage.setItem(k, thiz.asset[status][symbol]);
        localStorage.setItem(ktime, Date.now());
        console.log("刷新数据，存缓存：" + k + "----" + thiz.asset[status][symbol])
      })
    }
  })
}


//用户：
//1,1个D（Kio或kis）兑换1%池子里面的金额, approve;  kio(kis) 兑换 奖金池
//2, 燃烧A得到C，如果24小时没人处理，则最后一人可以领取所有 
/**
 * 兑换 和直接领取
 * @param {*} symbol 
 * @param {*} isSafeTransfer 
 */
Vue.prototype.$convert = async function (symbol, isSafeTransfer, isGet) {

  if (!isGet && this.asset.b[symbolConvertMap[symbol]] < 1) {
    this.$alert(symbolConvertMap[symbol] + '可用数量不足')
    return
  }
  this.$showLoding(true)
  this.$tronSend(addrMap[symbol], covertFname[symbol], 0, isSafeTransfer).then(b => {
    if (b == undefined) {
      if (isGet) {
        if (symbol == 'kid') {
          this.stg1info.bonus = 0
        } else {
          this.stg2info.bonus = 0
        }
      }
      this.$showSuccess(this.$t('popup.exchangeSuccessed'))
      this.$updateAsset('usdt', "b", true);
      this.$updateAsset(symbol == 'kid' ? 'kio' : 'kis', "b", true);
    } else {
      this.$showFail(this.$t('popup.fail'))
    }
  }).catch(err => {
    this.$showFail(err.message)
  })
}







new Vue({
  router,
  i18n,
  render: (h) => h(App),
}).$mount("#app");
